package com.dqy.twserver.server.handle.ehandle;

import com.dqy.twserver.server.dto.GameDto;
import com.dqy.twserver.server.handle.ehandle.hook.GameEventPlayUnregisteredHandle;
import com.dqy.twserver.server.support.Constans;
import com.dqy.twserver.server.support.MsgPush;
import com.dqy.twserver.server.support.Player;
import com.dqy.twserver.server.support.SupportMap;
import com.dqy.twserver.server.support.data.RoomInfo;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

public class GameEventStartHandle implements GameEventHandle{
    static Logger logger = LoggerFactory.getLogger(GameEventStartHandle.class);
    static Random random=new Random();
    @Override
    public void handle(GameDto req, NioSocketChannel channel) throws Exception {
        logger.info("[GameEventStartHandle] start");

        String roomId = req.getRoomId();
        String playerName = req.getPlayerName();

        int rid = roomIdToRid(roomId);
        //校验该玩家的请求是否合法（只有房主才能开始）
        Map<Integer, RoomInfo> roomMap = SupportMap.roomMap;
        RoomInfo roomInfo = roomMap.get(rid);

        //利用&&短路来进行连续校验(房间是否存在->是否房主->玩家人数是否大于1)
        if(         check(roomInfo!=null,"该房间不存在",channel)
                || check(roomInfo.getRoomCreateUser().equals(playerName),"你不是房主，不能直接开始",channel)
                || check(roomInfo.getPlayerList().size()>=2,"不能开始，原因[玩家至少大于1人]",channel)){
            return;
        }

        //检查是否全部准备完成
        List<Player> checkRescue = roomInfo.getPlayerList().stream().filter(i -> i.getPlayReadi() == 0).collect(Collectors.toList());
        if( check(checkRescue.size()==0,"不能开始，原因[有玩家尚未准备]",channel)) return;

        ///////////检验全部通过//////////////
        logger.info("[GameEventStartHandle] 校验通过，{} 该房间已经满足开始条件",roomId);

        GameDto resp = GameDto.build(200, "ok", -1);
        roomInfo.setRoomSts("1");
        channel.writeAndFlush(resp);

        List<Player> playerList = roomInfo.getPlayerList();
        for (int i = 0; i <playerList.size() ; i++) { //給房间中的每位玩家分配颜色编号
            playerList.get(i).setPlayerColor(i+1);
        }

        //向房间内其他玩家推送一条游戏开始的消息
        MsgPush.sendMsg(playerList,"游戏开始:","info", Constans.EVENT_TYPE_SEND_GAME_IS_START);

        logger.info("[GameEventStartHandle] end");
    }

    //校验器，当b为假，表示校验不通过
    private boolean check(boolean b,String respInfo,NioSocketChannel channel){
        if(!b){
            GameDto resp = GameDto.build(400, respInfo, -1);
            channel.writeAndFlush(resp);
            logger.info("[GameEventStartHandle] err->{}",respInfo);
        }
        return !b;
    }
}
